package com.nahan.secondapplication.goodsdetail.fragment;


import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import androidx.fragment.app.Fragment;

import com.nahan.secondapplication.R;
import com.nahan.secondapplication.goodsdetail.widget.PageOneScrollView;
import com.nahan.secondapplication.goodsdetail.widget.PageTwoWebView;
import com.nahan.secondapplication.goodsdetail.widget.SlidingDetailsLayout;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * 商品界面
 * A simple {@link Fragment} subclass.
 */
public class GoodsDetailFragment extends Fragment {
    private static final String TAG = "GoodsDetailFragment";
    @BindView(R.id.slidingDetailsLayout)
    SlidingDetailsLayout slidingDetailsLayout;
    @BindView(R.id.tishi)
    TextView tishi;
    @BindView(R.id.webview)
    PageTwoWebView webview;
    @BindView(R.id.sc_all)
    PageOneScrollView sc_all;


    @BindView(R.id.tv_miaosha_time)
    TextView mMiaoshaTimeTv;
    @BindView(R.id.tv_miaosha_shi)
    TextView mMiaoshaShiTv;
    @BindView(R.id.tv_miaosha_minter)
    TextView mMiaoshaMinterTv;
    @BindView(R.id.tv_miaosha_second)
    TextView mMiaoshaSecondTv;

    private String mUrl = "http://www.baidu.com/";


    public interface ScrollChangeListener
    {
        void ScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY);
    }
    public ScrollChangeListener scrollChangeListener;
    public void setScrollChange(ScrollChangeListener scrollChangeListener)
    {
        this.scrollChangeListener=scrollChangeListener;
    }

    private static GoodsDetailFragment fragment = null;

    public static GoodsDetailFragment newInstance() {
        if (fragment == null) {
            fragment = new GoodsDetailFragment();
        }
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_goods_detail, container, false);
        ButterKnife.bind(this, view);
        initView();
        initWebView();
        handler.sendEmptyMessage(0);
        return view;
    }

    @SuppressLint("NewApi")
    private void initWebView() {
        WebSettings settings = webview.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);

        settings.setDomStorageEnabled(true);// 设置可以使用localStorage
        webview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        webview.loadUrl(mUrl);
        webview.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                //这句话说的意思告诉父View我自己的事件我自己处理
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webview.setWebViewClient(new WebViewClient() {

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                String scheme = url.substring(0, 4).trim().toLowerCase();
                if (scheme.contains("https") || scheme.contains("http")) {
                    view.loadUrl(url);
                }
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                int w = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                int h = View.MeasureSpec.makeMeasureSpec(0,
                        View.MeasureSpec.UNSPECIFIED);
                //重新测量
                webview.measure(w, h);
            }
        });


        sc_all.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                scrollChangeListener.ScrollChange( v,  scrollX,  scrollY,  oldScrollX, oldScrollY);
            }
        });
    }

    private void initView() {
        tishi.setText("上拉查看商品详情");
        slidingDetailsLayout.setPositionChangListener(new SlidingDetailsLayout.PositionChangListener() {
            @Override
            public void position(int positon) {
                if (positon == 0) {
                    tishi.setText("上拉查看商品详情");
                } else {
                    tishi.setText("下拉返回商品简介");

                }
            }

            @Override
            public void onBottom() {
                tishi.setText("松开，马上加载商品详情");
            }

            @Override
            public void backBottom() {
                tishi.setText("上拉查看商品详情");
            }

            @Override
            public void onTop() {
                tishi.setText("松开，返回商品简介");
            }

            @Override
            public void backTop() {
                tishi.setText("下拉返回商品简介");
            }
        });
    }


    //使用handler用于更新UI
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            countDown();
            sendEmptyMessageDelayed(0, 1000);
        }
    };
    /**
     * 秒杀
     */
    private void countDown() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date curDate = new Date(System.currentTimeMillis());
        String format = df.format(curDate);
        StringBuffer buffer = new StringBuffer();
        String substring = format.substring(0, 11);
        buffer.append(substring);
        Log.d("ccc", substring);
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        if (hour % 2 == 0) {
            mMiaoshaTimeTv.setText(hour + "点场");
            buffer.append((hour + 2));
            buffer.append(":00:00");
        } else {
            mMiaoshaTimeTv.setText((hour - 1) + "点场");
            buffer.append((hour + 1));
            buffer.append(":00:00");
        }
        String totime = buffer.toString();
        try {
            java.util.Date date = df.parse(totime);
            java.util.Date date1 = df.parse(format);
            long defferenttime = date.getTime() - date1.getTime();
            long days = defferenttime / (1000 * 60 * 60 * 24);
            long hours = (defferenttime - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            long minute = (defferenttime - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
            long seconds = defferenttime % 60000;
            long second = Math.round((float) seconds / 1000);
            mMiaoshaShiTv.setText("0" + hours + "");
            if (minute >= 10) {
                mMiaoshaMinterTv.setText(minute + "");
            } else {
                mMiaoshaMinterTv.setText("0" + minute + "");
            }
            if (second >= 10) {
                mMiaoshaSecondTv.setText(second + "");
            } else {
                mMiaoshaSecondTv.setText("0" + second + "");
            }


        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
